<template>
  <a-form class="filer-wrap">
    <a-form-item >
      <a-button type="primary" @click="funcOperate()">新增</a-button>
    </a-form-item>
    <a-form-item >
      <a-tooltip>
        <template #title>将函数导出为 ESM 规范的js文件</template>
        <a-button type="primary" @click="exportFunctions">导出</a-button>
      </a-tooltip>
    </a-form-item>
    <a-form-item >
      <a-input  placeholder="搜索函数" />
    </a-form-item>
    <a-form-item >
      <a-select  v-model:value="value1" style="width: 120px" placeholder="筛选函数">
        <a-select-option value="jack">标签一</a-select-option>
        <a-select-option value="lucy">标签二</a-select-option>
        <a-select-option value="disabled">标签三</a-select-option>
        <a-select-option value="Yiminghe">标签四</a-select-option>
      </a-select>
    </a-form-item>
    <a-form-item >
      <a-tooltip>
        <template #title>同步界面与本地文件的内容</template>
        <a-button type="primary" @click="reLoadFunctions">刷新</a-button>
      </a-tooltip>
    </a-form-item>
  </a-form>
  <!-- modal of export-->
  <a-modal :visible="showExport" @cancel="showExport = false" @ok="exportConfirm" width="50%" height="500px">
    <a-transfer
        style="width: 100%"
        :data-source="allFunctions"
        show-search
        :titles="['', '导出列表']"
        :operations="['导出', '取消']"
        :filter-option="filterOption"
        :target-keys="targetKeys"
        :render="item => item.name"
        @change="handleChange"
    />
    <div class="export-name">
      导出文件名：<a-input v-model:value="exportName" style="width: 50%"></a-input>
    </div>
  </a-modal>
</template>

<script setup>
import {saveAs} from 'file-saver'

import { defineEmit,  unref, useContext} from 'vue'
import {  reactive, ref} from 'vue'
import {exportESMFunctions, getLocalFunctions} from "../../../api/index";
import {storage} from "../../../utils/storage";
import {message} from "ant-design-vue";
defineEmit(['funcOperate','updateList'])
const {emit} = useContext()

/**
 * onclick the add button
 *
 * emit to father to show add modal
 */
const funcOperate = ()=>{
  emit('funcOperate',{
    type:'add',
    record: ''
  })
}

/**
 * onclick the reload button
 *
 * refresh storage ,then update the view
 */
const reLoadFunctions = async ()=>{
  await  getLocalFunctions(true)
  message.success('函数刷新成功')
  emit('updateList')
}

/**
 * onclick the export button
 *
 * show the modal,then get functions from storage
 */
const showExport = ref(false) // whether show the modal for export
const exportFunctions = async ()=>{
  showExport.value = true
  getFunctions()
}
// get functions from storage
const getFunctions = ()=>{
  const funcMap = storage.local.get('keyMap') || []
  const list = funcMap.map(item=>{
    let func = storage.local.get(item)
    func.title=''
    func.key = func.key.toString()
    return func
  })
  allFunctions.value = list
  targetKeys.value = unref(allFunctions).map(item=>item.key)
}

/**
 * export functions
 *
 * get codes from storage,and transform to String
 * then call Node.js api with codes and name
 */
const exportName = ref('jsLibs'); // name of the file to be exported
let allFunctions = ref([])  // functions in the storage
const targetKeys = ref([]); // keys of functions to be exported
const exportConfirm = async ()=>{
  const codes = unref(allFunctions) // String of functions to be exported
                .filter(func=>unref(targetKeys).includes(func.key))
               .map(item=> unref(item).code).join('//**//')
  const name = unref(exportName)
  const res = await exportESMFunctions({codes,name});
  showExport.value = true

  if(res.type === 'success'){
    message.success('文件导出成功，导出路径为:' + res.msg)
    var file = new File([res.content], name , {type: "text/javascript;charset=utf-8"});
    saveAs(file);
  }else{
    const msg = res.msg || res
    message.error('文件导出失败:' + msg)
  }
}
// query functions when export
const filterOption = (inputValue, option) => {
  return option.name.indexOf(inputValue) > -1;
};
// handle functions before export
const handleChange = (keys, direction, moveKeys) => {
  targetKeys.value = keys;
};

/**
 * data for query functions
 */
// const filterData = reactive({
//   name: '',
//   remark: undefined,
//   tag: undefined,
// })


</script>

<style scoped lang="less">
.filer-wrap{
  display: flex;
  width: 100%;
  justify-content: space-around;
}
.export-name{
  width: 30%;
  min-width: 250px;
  position: absolute;
  bottom: 10px;
  right: 25%;
}
::v-deep .ant-transfer-list{
  width: calc(50% - 50px);
  height: 350px;
  margin-top: 30px;
}
::v-deep .ant-transfer-operation{
  width: 70px;
  margin: 0 15px;
}
</style>
